package model

type LuckServer interface {
	Create(power *Luck) (err error)
	Update(power Luck, column string, value interface{}) error
	UpdateAll(power Luck) error
	UpdateBig(power Luck) error
	GetCountSend(openId string) int
	GetCount(openId string) int
}

type luckServer struct {
}

func NewLuckServer() LuckServer {
	return &luckServer{}
}

func (u *luckServer) Create(power *Luck) (err error) {
	sql := "INSERT INTO luck_remain (open_id, remain_time, update_time, subscribe_time ) VALUES (?, ?, ?, ?)"
	stmt, err := Db.Prepare(sql)
	if err != nil {
		return
	}
	defer stmt.Close()

	res, err := stmt.Exec(power.OpenId, power.RemainTime, power.UpdateTime, power.SubscribeTime)
	if err != nil {
		return
	}
	id, err := res.LastInsertId()
	if err != nil {
		return
	}
	power.Id = int(id)
	return nil
}

func (u *luckServer) Update(power Luck, column string, value interface{}) (err error) {
	statement := "UPDATE luck_remain SET " + column + " = ? WHERE open_id = ?"
	stmt, err := Db.Prepare(statement)
	if err != nil {
		return
	}
	defer stmt.Close()

	_, err = stmt.Exec(value, power.OpenId)
	return
}

func (u *luckServer) GetCountSend(openId string) (count int) {
	_ = Db.QueryRow("SELECT count(id) FROM luck_remain WHERE open_id = ? AND send_time = 0", openId).Scan(&count)
	return
}

func (u *luckServer) GetCount(openId string) (count int) {
	_ = Db.QueryRow("SELECT count(id) FROM luck_remain WHERE open_id = ? ", openId).Scan(&count)
	return
}

func (u *luckServer) UpdateAll(power Luck) (err error) {
	statement := "UPDATE luck_remain SET remain_time = ?, send_time = ?, update_time = ?, subscribe_time = ? WHERE open_id = ?"
	stmt, err := Db.Prepare(statement)
	if err != nil {
		return
	}
	defer stmt.Close()

	_, err = stmt.Exec(power.RemainTime, power.SendTime, power.UpdateTime, power.SubscribeTime, power.OpenId)
	return
}

func (u *luckServer) UpdateBig(power Luck) (err error) {
	statement := "UPDATE luck_remain SET remain_time = ?, update_time = ? WHERE open_id = ?"
	stmt, err := Db.Prepare(statement)
	if err != nil {
		return
	}
	defer stmt.Close()

	_, err = stmt.Exec(power.RemainTime, power.UpdateTime, power.OpenId)
	return
}
